#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
演示脚本
展示客户端与ESP32服务端的自动化通信
"""

import time
import threading
from client import SecureClient

def demo_communication():
    """
    演示通信功能
    """
    print("=== 通信演示 ===")
    
    client = SecureClient()
    
    try:
        # 连接到服务器
        print("1. 连接到ESP32服务器...")
        if not client.connect_to_server():
            print("连接失败，演示结束")
            return
        
        print("\n2. 测试ping通信...")
        client.ping_server()
        time.sleep(1)
        
        print("\n3. 请求传感器数据...")
        sensor_data = client.request_sensor_data()
        time.sleep(1)
        
        print("\n4. 发送控制命令...")
        client.send_control_command("turn_on_led")
        time.sleep(1)
        
        client.send_control_command("set_temperature_25")
        time.sleep(1)
        
        print("\n5. 再次获取传感器数据...")
        sensor_data = client.request_sensor_data()
        time.sleep(1)
        
        print("\n演示完成！")
        
    except Exception as e:
        print(f"演示过程中出错：{e}")
    finally:
        client.disconnect()

def stress_test():
    """
    压力测试 - 多个客户端同时连接
    """
    print("\n=== 压力测试 ===")
    
    def client_worker(client_id):
        client = SecureClient()
        try:
            if client.connect_to_server():
                print(f"客户端 {client_id} 连接成功")
                
                # 执行一些操作
                for i in range(3):
                    client.ping_server()
                    time.sleep(0.5)
                    client.request_sensor_data()
                    time.sleep(0.5)
                
                print(f"客户端 {client_id} 测试完成")
            else:
                print(f"客户端 {client_id} 连接失败")
        except Exception as e:
            print(f"客户端 {client_id} 出错：{e}")
        finally:
            client.disconnect()
    
    # 创建多个客户端线程
    threads = []
    for i in range(3):
        thread = threading.Thread(target=client_worker, args=(i+1,))
        threads.append(thread)
        thread.start()
        time.sleep(0.1)  # 稍微错开连接时间
    
    # 等待所有线程完成
    for thread in threads:
        thread.join()
    
    print("压力测试完成！")

def main():
    print("=== ESP32混合加密通信演示 ===")
    print("请确保ESP32服务器已启动 (运行 esp32_server.py)")
    input("按回车键开始演示...")
    
    # 基本通信演示
    demo_communication()
    
    # 询问是否进行压力测试
    response = input("\n是否进行压力测试？(y/n): ")
    if response.lower() == 'y':
        stress_test()
    
    print("\n演示结束！")

if __name__ == "__main__":
    main()